﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Model.Entities;
using Totoro.ORMapping;
using NHibernate;
using NHibernate.Criterion;

namespace Bussiness
{
    [Serializable]
    public static class OrderBusiness
    {
        public static bool CheckIsUserLogin()
        {
            //HttpCookie c = HttpContext.Current.Request.Cookies["tt_ticket"];
            //User u = (User)HttpContext.Current.Session["CurrentUser"];
            //return c!= null && u != null && !string.IsNullOrEmpty(u.ID);
            return Permission.IsAuthenticated;
        }

        public static void CreateOrderWithLoginUser(OrderVOParameters parameters)
        {
            try
            {
                //Validate if parameters are valid
                if (HttpContext.Current.Session["CurrentUser"] == null 
                    ||string.IsNullOrEmpty(HttpContext.Current.Session["CurrentUser"].ToString()))
                {
                    throw new Exception("Invalid Session.");
                }
                if (string.IsNullOrEmpty(parameters.AddressDetail))
                {
                    throw new Exception("Address should not be empty.");
                }
                if (string.IsNullOrEmpty(parameters.Phone))
                {
                    throw new Exception("Phone number should not be empty.");
                }
                if (parameters.ProductsInfo == null || parameters.ProductsInfo.Count == 0)
                {
                    throw new Exception("You should order food first.");
                }

                using (ITransaction transaction = NHHelper.GetCurrentSession().BeginTransaction())
                {
                    User currentUser = (User)HttpContext.Current.Session["CurrentUser"];
                    //Create an Order
                    Model.Entities.Order order = new Model.Entities.Order();
                    order.AddressArea = parameters.AddressArea;
                    order.AddressDetail = parameters.AddressDetail;
                    order.CreateTime = DateTime.Now;
                    order.FinishTime = DateTime.MaxValue;
                    order.PayType = parameters.PayType;
                    order.Phone = parameters.Phone;
                    order.UserID = currentUser.ID;
                    order.OrderSerial = System.Guid.NewGuid().ToString();
                    //order.State  order.Remarks order.IsPayed related paytype
                    NHHelper.SaveOjb(order);

                    //Create OrderDetail
                    foreach (OrderedProducts eachProduct in parameters.ProductsInfo)
                    {
                        OrderDetail orderdetails = new OrderDetail();
                        orderdetails.OrderID = order.ID;
                        orderdetails.ProductID = eachProduct.ProductID;
                        orderdetails.Quantity = eachProduct.Quantity;
                        orderdetails.ProductPrice = eachProduct.ProductPrice;
                        orderdetails.ProductName = eachProduct.ProductName;
                        orderdetails.CreateTime = DateTime.Now;
                        orderdetails.FinishTime = DateTime.MaxValue;
                        //orderdetails.State  orderdetails.Remarks
                        NHHelper.SaveOjb(orderdetails);
                    }

                    transaction.Commit();
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                NHHelper.CloseSession();
            }
        }

        public static void CreateOrderWithNonLoginUser(OrderVOParameters parameters)
        {
            try
            {
                //Validate if parameters are valid
                if (string.IsNullOrEmpty(parameters.AddressDetail))
                {
                    throw new Exception("Address should not be empty.");
                }
                if (string.IsNullOrEmpty(parameters.Phone))
                {
                    throw new Exception("Phone number should not be empty.");
                }
                if (parameters.ProductsInfo == null || parameters.ProductsInfo.Count == 0)
                {
                    throw new Exception("You should order food first.");
                }

                //Get UserID if this user is already created in DB
                User currentUser = new User();
                ISession session = NHHelper.GetCurrentSession();

                using (ITransaction transaction = session.BeginTransaction())
                {
                    ICriteria cr = session.CreateCriteria<User>();
                    cr.Add(Expression.Eq("LogonName", parameters.Phone));
                    IList<User> lst = cr.List<User>();
                    if (lst.Count > 0)
                    {
                        currentUser = lst[0] as User;
                    }
                    //Create a visitor into User table if not find in DB
                    else
                    {
                        currentUser.LogonName = parameters.Phone;
                        currentUser.PassWord = "";
                        currentUser.CreateTime = DateTime.Now;
                        currentUser.EndTime = DateTime.MaxValue;
                        currentUser.UpdateTime = DateTime.Now;
                        NHHelper.SaveOjb(currentUser);
                    }

                    //Create an Order
                    Model.Entities.Order order = new Model.Entities.Order();
                    order.AddressArea = parameters.AddressArea;
                    order.AddressDetail = parameters.AddressDetail;
                    order.CreateTime = DateTime.Now;
                    order.FinishTime = DateTime.MaxValue;
                    order.PayType = parameters.PayType;
                    order.Phone = parameters.Phone;
                    order.UserID = currentUser.ID;
                    //order.State  order.Remarks order.IsPayed related paytype
                    order.OrderSerial = System.Guid.NewGuid().ToString();
                    NHHelper.SaveOjb(order);

                    //Create OrderDetail
                    foreach (OrderedProducts eachProduct in parameters.ProductsInfo)
                    {
                        OrderDetail orderdetails = new OrderDetail();
                        orderdetails.OrderID = order.ID;
                        orderdetails.ProductID = eachProduct.ProductID;
                        orderdetails.Quantity = eachProduct.Quantity;
                        orderdetails.ProductPrice = eachProduct.ProductPrice;
                        orderdetails.ProductName = eachProduct.ProductName;
                        orderdetails.CreateTime = DateTime.Now;
                        orderdetails.FinishTime = DateTime.MaxValue;
                        //orderdetails.State  orderdetails.Remarks
                        NHHelper.SaveOjb(orderdetails);
                    }
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                NHHelper.CloseSession();
            }
        }
    }

    public class OrderVOParameters
    {
        public string Phone;
        public string AddressArea;
        public string AddressDetail;
        public int PayType;
        public List<OrderedProducts> ProductsInfo;
    }

    public class OrderedProducts
    {
        public int Quantity;
        public string ProductID;
        /***Why do we need these info?? **/
        public string ProductName;
        public string ProductPrice;
    }
}
